<template>
  <div class="employee-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <el-button type="primary" @click="showAddDialog">新增员工</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" inline>
        <el-form-item label="姓名">
          <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="工号">
          <el-input v-model="queryParams.jobNumber" placeholder="请输入工号" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryParams.roleId" placeholder="请选择角色" clearable>
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 员工表格 -->
      <el-table :data="employeeList" border stripe>
        <el-table-column prop="jobNumber" label="工号" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="roleName" label="角色" width="120" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{row}">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === 1 ? 'danger' : 'success'" 
              @click="toggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" @click="handleResetPassword(row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getEmployeeList, 
  addEmployee, 
  updateEmployee, 
  resetPassword, 
  changeStatus 
} from '@/api/employee'
import { getRoleList } from '@/api/role'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  jobNumber: '',
  roleId: null,
  status: null
})

// 表格数据
const employeeList = ref<any[]>([])
const total = ref(0)
const roleList = ref<any[]>([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  jobNumber: '',
  name: '',
  roleId: null,
  phone: '',
  status: 1
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
})

// 获取员工列表
const fetchEmployeeList = async () => {
  try {
    const res = await getEmployeeList(queryParams)
    console.log(res)
    employeeList.value = res.data.records
    employeeList.value.forEach(item => {
      item.roleName = roleList.value.find(role => role.id === item.roleId)?.roleName
    })
    total.value = res.data.total
  } catch (error) {
    console.error('获取员工列表失败:', error)
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await getRoleList()
    roleList.value = res.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchEmployeeList()
}

// 重置搜索
const resetSearch = () => {
  queryParams.pageNum = 1
  queryParams.name = ''
  queryParams.jobNumber = ''
  queryParams.roleId = null
  queryParams.status = null
  fetchEmployeeList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  fetchEmployeeList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  fetchEmployeeList()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增员工'
  form.jobNumber = ''
  form.name = ''
  form.roleId = null
  form.phone = ''
  form.status = 1
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑员工'
  form.jobNumber = row.jobNumber
  form.name = row.name
  form.roleId = row.roleId
  form.phone = row.phone
  form.status = row.status
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (form.jobNumber) {
      await updateEmployee(form)
      ElMessage.success('员工信息更新成功')
    } else {
      await addEmployee(form)
      ElMessage.success('员工添加成功')
    }
    
    dialogVisible.value = false
    fetchEmployeeList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 切换状态
const toggleStatus = (row: any) => {
  const newStatus = row.status === 1 ? 0 : 1
  ElMessageBox.confirm(
    `确定要${newStatus === 1 ? '启用' : '禁用'}该员工吗?`,
    '提示',
    { type: 'warning' }
  ).then(async () => {
    await changeStatus(row.id, newStatus)
    ElMessage.success('状态修改成功')
    fetchEmployeeList()
  }).catch(() => {})
}

// 重置密码
const handleResetPassword = (row: any) => {
  ElMessageBox.confirm(
    '确定要将密码重置为123456吗?',
    '重置密码',
    { type: 'warning' }
  ).then(async () => {
    await resetPassword(row.id)
    ElMessage.success('密码重置成功')
  }).catch(() => {})
}

onMounted(() => {
  fetchRoleList()
  fetchEmployeeList()
})
</script>

<style scoped>
.employee-management {
  padding: 20px;
}
</style>